<template>
    <MainSlot>
        <template v-slot:searchForm>
            <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag"
                @search="search" @isUnfold="(v) => { unfoldFlag = v }">
            </SearchForm>
        </template>
        <template v-slot:btn>
            <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
        </template>
        <template v-slot:table>
            <TableData v-loading="loading" :configFixed="{ flag: 'right' }" :config="table_config"
                :tableThead="tableThead" :dataList="dataList" @selection-change="selectionChange">
                <template v-slot:inputPondId="{ row }">
                    <span v-show="!row.inputPondId" class="successText">未使用</span>
                    <span v-show="row.inputPondId" class="errorText">已使用</span>
                </template>
                <template v-slot:anum="{ row }">
                    <span v-if="row.num">
                        {{ row.materialId ? row.num / materialObj[row.materialId].ratioNum : "" }}
                        {{ row.materialId ? materialObj[row.materialId].aUnit : "" }}
                    </span>
                    <span v-else>--</span>
                </template>
                <template v-slot:num="{ row }">
                    {{ row.num || '--' }}{{ row.materialId ? materialObj[row.materialId].unit : "" }}
                </template>
                <template v-slot:codeNumber="{ row }">
                    {{ row.codeNumber || '--' }}
                </template>
            </TableData>
        </template>
        <template v-slot:pagination>
            <Pagination @current-change="handleCurrentChange" :page="page" :total="total">
            </Pagination>
        </template>
        <template v-slot:dialogModule>
            <AddEdit :title="'投喂'" :batchList="batchList" :materialList="materialList" :fishPondList="fishPondList"
                :fishVarietyList="fishVarietyList" :specificationList="specificationList" :staffList="staffList"
                @closeDialog="closeDialog" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible" :data="formData">
            </AddEdit>
        </template>
    </MainSlot>
</template>
<script>
import store from "@/store";
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import SearchForm from '@/components-production-management/SearchForm';
import TableData from '@/components-production-management/TableData';
import BtnSlot from '@/components-production-management/BtnSlot';
import EnumSlot from '@/components-production-management/EnumSlot';
import AddEdit from './components/addEdit.vue';
//批次
import batchManagement from '@/api/production-management/batch-management.js';
//鱼塘
import fishPondApi from "@/api/basic-info-manage/fishPond";
//投喂接口
import feedingOperation from '@/api/production-management/feeding-operation.js';
//品种
import fishVarietyApi from "@/api/basic-info-manage/fishVariety"
//规格
import specificationApi from "@/api/basic-info-manage/specification/index";
//获取员工
import staffApi from "@/api/basic-info-manage/staff";
//物料
import MaterialApi from "@/api/basic-info-manage/material";
export default {
    components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot, AddEdit },
    data() {
        return {
            unfoldFlag: false,
            loading: false,
            dialogVisible: false,
            dialogVisible_lookView: false,
            addEditFlag: 'add',
            selectList: [],
            unitList: [],
            formData: {},
            page: 1,
            total: 10,
            selectIndex: 0,
            searchFormData: {},
            btnList: ['add', 'delete'],
            dataList: [],
            tableThead: [
                { isShow: true, label: '鱼塘名称', prop: 'pondName', minWidth: '120px' },
                { isShow: true, label: '批次编号', prop: 'batchName', minWidth: '120px' },
                { isShow: true, label: '物料名称', prop: 'materialName', minWidth: '200px' },
                { isShow: true, label: '投喂量(主)', slotName: 'anum' },
                { isShow: true, label: '投喂量(辅)', slotName: 'num' },
                { isShow: true, label: '饲喂比', prop: 'materialToFish' },
                { isShow: true, label: '作业人', prop: 'staffName' },
                { isShow: true, label: '作业时间', prop: 'workDateTime', minWidth: '200px' },
                { isShow: true, label: '位置', prop: 'position' },
                { isShow: true, label: '季节', prop: 'season' },
                { isShow: true, label: '作业天数', prop: 'day' },
                { isShow: true, label: '作业次数', prop: 'time' }
            ],
            // 配置项
            table_config: {
                isCheckBox: true,
                isOperation: true,
                // 表格操作列
                operation: {
                    label: '操作',
                    width: '200',
                    cols: [
                        {
                            label: '编辑',
                            type: 'primary',
                            flag: 'edit',
                            handleRow: this.handleRow
                        },
                        {
                            label: '删除',
                            type: 'danger',
                            flag: 'del',
                            handleRow: this.handleRow
                        }
                    ]
                },
            },
            formItemList: [
                {
                    label: '鱼塘名称',
                    type: 'select',
                    selectOptions: [],
                    param: 'fishPondId',
                    defaultSelect: '', // 下拉框默认选中项
                    multiple: false,
                    isShow: true
                },
                {
                    label: '批次编号',
                    type: 'select',
                    selectOptions: [],
                    param: 'productionBatchId',
                    defaultSelect: '', // 下拉框默认选中项
                    multiple: false,
                    isShow: true
                },
                {
                    label: '物料名称',
                    type: 'select',
                    selectOptions: [],
                    param: 'materialId',
                    defaultSelect: '', // 下拉框默认选中项
                    multiple: false,
                    isShow: true
                },
                {
                    label: '作业人',
                    type: 'select',
                    selectOptions: [],
                    param: 'staffId',
                    defaultSelect: '', // 下拉框默认选中项
                    multiple: false,
                    isShow: true
                },
                {
                    label: '作业日期',
                    type: 'datetimerange',
                    param: 'dateTime',
                    multiple: false,
                    isShow: true
                },
            ],
            fishPondList: [],
            batchList: [],
            allbatchList: [],
            staffList: [],
            specificationList: [],
            fishVarietyList: [],
            breedTypeList: [],
            materialList: [],
            breedTypeObj: {}
        }
    },
    computed: {
        materialObj() {
            console.log(store.state.basicData.material)
            return store.state.basicData.material;
        }
    },
    mounted() {
        this.queryPageByCondition();
        this.initData();
    },
    methods: {
        //初始化数据
        async initData() {
            let { data: materialList } = await MaterialApi.queryByCondition({ materialTypeNo: 'FEED' }) //物料
            let { data: fishPondList } = await fishPondApi.queryByCondition({ bindBatch: true });//查询鱼塘列表 //bindBatch:true 查询绑定了批次的鱼塘
            let { data: batchList } = await batchManagement.queryByCondition({ unCompleteBatch: true });//查询批次列表
            let { data: allbatchList } = await batchManagement.queryByCondition();//查询批次列表
            let { data: fishVarietyList } = await fishVarietyApi.queryByCondition();//查询品种
            let { data: specificationList } = await specificationApi.queryByCondition();//查询规格
            let { data: staffList } = await staffApi.queryByCondition()
            this.fishPondList = fishPondList || [];
            this.batchList = batchList || [];
            this.allbatchList = allbatchList || [];
            this.fishVarietyList = fishVarietyList || [];
            this.specificationList = specificationList || [];
            this.materialList = materialList || [];
            this.staffList = staffList || [];
            this.setFormOptions();
        },
        setFormOptions() {
            let list = JSON.parse(JSON.stringify(this.formItemList));
            this.formItemList = []
            list.forEach((item, index) => {
                if (item.param.indexOf('fishPondId') !== -1) {
                    let selectOptions = this.fishPondList.map(data => {
                        return {
                            text: data.pondName, value: data.fishPondId
                        }
                    })
                    item.defaultSelect = this.searchFormData[item.param];
                    item.selectOptions = selectOptions;
                };
                if (item.param.indexOf('staffId') !== -1) {
                    let selectOptions = this.staffList.map(data => {
                        return {
                            text: data.staffName, value: data.staffId
                        }
                    })
                    item.defaultSelect = this.searchFormData[item.param];
                    item.selectOptions = selectOptions;
                };
                if (item.param.indexOf('productionBatchId') !== -1) {
                    let selectOptions = this.allbatchList.map(data => {
                        return {
                            text: data.batchName, value: data.batchId
                        }
                    })
                    item.defaultSelect = this.searchFormData[item.param];
                    item.selectOptions = selectOptions;
                };
                if (item.param.indexOf('materialId') !== -1) {
                    let selectOptions = this.materialList.map(data => {
                        return {
                            text: data.name, value: data.materialId
                        }
                    })
                    item.defaultSelect = this.searchFormData[item.param];
                    item.selectOptions = selectOptions;
                };
            });
            this.$nextTick(() => {
                this.$set(this, 'formItemList', list)
                console.log(this.formItemList)
            })
        },
        //批量删除
        delList(deleteList = [], key = 'feedingWorkId') {
            let list = []
            deleteList.forEach(item => {
                list.push(item[key])
            })
            console.log(list)
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let res = await feedingOperation.delListById(list);
                if (res.success) {
                    this.$message.success(res.message || '删除成功');
                    this.queryPageByCondition();
                } else {
                    this.$message.warning(res.message || '删除失败');
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //查询
        queryPageByCondition() {
            let params = {
                page: this.page,
                size: 10,
                entity: {
                    ...this.searchFormData
                }
            }
            this.loading = true
            feedingOperation.queryPageByCondition(params).then(res => {
                this.loading = false
                if (res.success == 1) {
                    this.dataList = res.data.content || [];
                    this.total = res.data.totalElements;
                    if (res.data.totalPages && this.page > res.data.totalPages) {
                        this.page = res.data.totalPages;
                        this.queryPageByCondition();
                    }
                } else {
                    this.$message.warning(res.message || '分页查询失败')
                }
            }).catch(err => {
                this.loading = false
                console.log(err)
            })
        },
        //搜索
        search(data) {
            this.page = 1;
            let endData = null;
            let startData = null;
            if (data.dateTime && data.dateTime.length == 2) {
                startData = `${data.dateTime[0]} 00:00:00`;
                endData = `${data.dateTime[1]} 23:59:59`;
            }
            this.searchFormData = {
                ...this.searchFormData,
                ...data,
                workDateTimeStart: startData,
                workDateTimeEnd: endData
            };
            this.queryPageByCondition();
        },
        //翻页查询
        handleCurrentChange(page) {
            this.page = page;
            this.queryPageByCondition();
        },
        //查看详情
        lookView(row) {
            console.log(row)
            this.dialogVisible_lookView = true;
        },
        // table操作方法
        async handleRow(rowData, item) {
            if (item.flag == 'edit') {
                this.dialogVisible = await this.$getBatchStatus(rowData.productionBatchId);
                this.formData = JSON.parse(JSON.stringify(rowData))
            } else if (item.flag == 'del') {
                this.delList([rowData]);
            }
            this.addEditFlag = item.flag
        },
        // 多选方法
        selectionChange(val) {
            this.selectList = val || []
        },
        //获取选中Btn
        getBtnEvent(flag) {
            console.log(flag)
            if (flag == 'add') {
                this.dialogVisible = true
            } else if (flag == 'delete') {
                if (this.selectList.length > 0) {
                    this.delList(this.selectList);
                } else {
                    this.$message.warning('请先选择表单数据项后再删除！');
                }
            };
            this.addEditFlag = flag;
        },
        //关闭弹窗
        closeDialog(falg = true) {
            this.dialogVisible = false;
            falg && this.queryPageByCondition();
        },
    }
};
</script>
<style lang="scss" scoped></style>